package org.qfbl.netty.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {
    // 先定义一个channel组
    // GlobalEventExecutor.INSTANCE  全局的事件执行器，是一个单例
    private  static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private  static String format = "yyyy-MM-dd HH:mm:ss" ;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();

        channelGroup.forEach(ch ->{
            if(ch != channel){
                ch.writeAndFlush("[客户]" + channel.remoteAddress() + "发送消息：" + msg + "\n") ;
            }else{
                ch.writeAndFlush("[自己]发送了消息： " + msg + "\n") ;

            }

        });

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    // handlerAdded 表示连接一但被建立就第一个执行
    // 将当前的channel 加入channelGroup
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 将该客户加入聊天的信息推送到其他在线的客户端
        // 该方法会遍历group中的所有channel并发送消息
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + " 加入聊天\n") ;
        channelGroup.add(channel);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() +"上线了");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
//        channelGroup.remove(ctx.channel());
        channelGroup.writeAndFlush("[客户端] " + ctx.channel().remoteAddress() + "离开了") ;
        System.out.println("当前group的大小" + channelGroup.size());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "下线了");
    }
}
